import 'package:check_app/dao/task_dao.dart';
import 'package:check_app/model/taskInfo.dart';
import 'package:check_app/scoped_model/app_model.dart';
import 'package:check_app/util/pref_util.dart';
import 'package:check_app/widgets/TaskList.dart';
import 'package:flutter/material.dart';
import 'package:check_app/page/AddTaskPage.dart';
import 'package:check_app/page/TaskPage.dart';
import 'package:check_app/page/TempTaskPage.dart';
import 'package:check_app/widgets/SearchBar.dart';
import 'package:check_app/widgets/TabPages.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:scoped_model/scoped_model.dart';
import 'dart:convert' as convert;

const CHECHED_PATH = '/app/task/list/checked';
const PENDING_PATH = '/app/task/list/pending';

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new _HomePageState();
}

class _HomePageState extends State<HomePage> {
  bool _loading = false;
  List<String> tabTitles = [
    "待检验",
    "已检验",
  ];
  String keyword = '';
  int pendingPageNum = 1;
  int pendingPageSize = 10;
  int checkedPageNum = 1;
  int checkedPageSize = 10;
  int pendingTotal = 0;
  int checkedTotal = 0;
  List pendingList = [];
  List checkedList = [];

  @override
  void initState() {
    super.initState();
    getData(PENDING_PATH, 'pending');
    getData(CHECHED_PATH, 'checked');
  }

  Future<Null> getData(String path, String type) async {
    final connectionStatus =
        ScopedModel.of<GlobalModel>(context).connectionStatus;
    if (connectionStatus == 'ConnectivityResult.none') {
      return null;
    }
    setState(() {
      _loading = true;
    });
    try {
      var result = await TaskDao.fetchTaskList(path, {
        'keyword': keyword,
        'pageNum': type == 'pending' ? pendingPageNum : checkedPageNum,
        'pageSize': type == 'pending' ? pendingPageSize : checkedPageSize,
      });
      setState(() {
        _loading = false;
      });
      if (result.success) {
        if (type == 'pending') {
          tabTitles[0] = '待检验(' + result.total.toString() + ')';
          pendingTotal = result.total;
          for (var item in result.data) {
            var taskInfo =
                await PrefUtil().getString('task_' + item.id.toString());
            if (taskInfo != null) {
              int finishQuantity = 0;
              final taskInfoModel =
                  TaskInfo.fromJson(convert.jsonDecode(taskInfo));
              for (var value in taskInfoModel.subjectCollectList) {
                finishQuantity += value.finishQuantity;
              }
              item.finishQuantity = finishQuantity;
              item.hasInputAuth = true;
            } else {
              item.hasInputAuth = false;
            }
          }
          setState(() {
            pendingList.addAll(result.data);
          });
        } else if (type == 'checked') {
          tabTitles[1] = '已检验(' + result.total.toString() + ')';
          checkedTotal = result.total;
          setState(() {
            checkedList.addAll(result.data);
          });
        }
      } else {
        Fluttertoast.showToast(
          msg: result.message,
        );
      }
    } catch (e) {
      print(e);
      setState(() {
        _loading = false;
      });
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // backgroundColor: Color.fromRGBO(248, 248, 249, 1),
      body: SafeArea(
        child: Stack(
          children: <Widget>[
            Column(
              children: <Widget>[
                SearchBar(
                  placeHolder: "请输入任务编号或客户名称",
                  searchCb: (text) {
                    keyword = text;
                    pendingPageNum = 1;
                    checkedPageNum = 1;
                    pendingTotal = 0;
                    checkedTotal = 0;
                    pendingList = [];
                    checkedList = [];
                    getData(PENDING_PATH, 'pending');
                    getData(CHECHED_PATH, 'checked');
                  },
                ),
                Expanded(
                  flex: 1,
                  child: TabPages(
                    tabs: tabTitles,
                    pages: <Widget>[
                      TaskList(
                        total: pendingTotal,
                        list: pendingList,
                        upRefresh: () {
                          pendingPageNum += 1;
                          getData(PENDING_PATH, 'pending');
                        },
                        onclick: (item) async {
                          if (item.type == 'NORMAL') {
                            await Navigator.of(context)
                                .push(MaterialPageRoute(builder: (_) {
                              return TaskPage(code: item.code, id: item.id);
                            }));
                          } else if (item.type == 'EXTRA') {
                            await Navigator.of(context)
                                .push(MaterialPageRoute(builder: (_) {
                              return TempTaskPage(code: item.code, id: item.id);
                            }));
                          }

                          final connectionStatus =
                              ScopedModel.of<GlobalModel>(context)
                                  .connectionStatus;
                          if (connectionStatus == 'ConnectivityResult.none') {
                            final taskInfo = await PrefUtil()
                                .getString('task_' + item.id.toString());
                            if (taskInfo != null) {
                              int finishQuantity = 0;
                              final taskInfoModel = TaskInfo.fromJson(
                                  convert.jsonDecode(taskInfo));
                              for (var value
                                  in taskInfoModel.subjectCollectList) {
                                finishQuantity += value.finishQuantity;
                              }
                              setState(() {
                                item.finishQuantity = finishQuantity;
                                item.hasInputAuth = true;
                              });
                            }
                          } else {
                            pendingPageNum = 1;
                            checkedPageNum = 1;
                            pendingTotal = 0;
                            checkedTotal = 0;
                            pendingList = [];
                            checkedList = [];
                            getData(PENDING_PATH, 'pending');
                            getData(CHECHED_PATH, 'checked');
                          }
                        },
                      ),
                      TaskList(
                        total: checkedTotal,
                        list: checkedList,
                        upRefresh: () {
                          checkedPageNum += 1;
                          getData(CHECHED_PATH, 'checked');
                        },
                        onclick: (item) {
                          if (item.type == 'NORMAL') {
                            Navigator.of(context)
                                .push(MaterialPageRoute(builder: (_) {
                              return TaskPage(code: item.code, id: item.id);
                            }));
                          } else if (item.type == 'EXTRA') {
                            Navigator.of(context)
                                .push(MaterialPageRoute(builder: (_) {
                              return TempTaskPage(code: item.code, id: item.id);
                            }));
                          }
                        },
                      ),
                    ],
                  ),
                ),
              ],
            ),
            Positioned(
              right: 16,
              bottom: 20,
              child: GestureDetector(
                onTap: () async {
                  await Navigator.of(context)
                      .push(MaterialPageRoute(builder: (_) {
                    return AddTaskPage();
                  }));
                  pendingPageNum = 1;
                  pendingTotal = 0;
                  pendingList = [];
                  getData(PENDING_PATH, 'pending');
                },
                child: Container(
                  width: 32,
                  height: 32,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    color: Color.fromRGBO(89, 131, 252, 1),
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: Image(
                    image: AssetImage('assets/images/add.png'),
                    width: 12,
                    height: 12,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
